import json
from django.conf import settings
from django.contrib.auth import login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse, HttpResponseForbidden,JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from itsdangerous import TimedJSONWebSignatureSerializer
from celery_tasks.email.tasks import SendEmail
from .forms import RegisterForm,LoginForm,ForgetForm,ModifyPwdForm,UserInfoForm
from django.views import View
from .models import UserProfile
from datetime import datetime
# 退出
class LogoutView(View):
    def get(self,request):
        logout(request)
        return redirect(reverse('login'))
# 注册
class RegisterView(View):
    def get(self,request):
        register_form = RegisterForm()
        return render(request, 'register.html', {'register_form': register_form})

    def post(self,request):
        # 获取表单数据
        data = request.POST
        data_dict = data.dict()
        # 生成表单对象
        register_form = RegisterForm(data)
        # 验证表单
        res = register_form.is_valid()
        # 可以通过error属性获取验证失败的原因
        error=register_form.errors
        print(error)
        if res:
            # 链接数据库判断用户名是否存在
            try:
                UserProfile.objects.get(email=data_dict['email'])
            except:
                # 验证成功则保存数据
                user = UserProfile.objects.create(email = data_dict['email'],
                password=data_dict['password'],username=data_dict['email'])
                login(request,user)
                response = redirect(reverse('index'))
                response.set_cookie("username",data_dict['email'])
                return response
            return HttpResponseForbidden("用户名存在")
        # 验证失败返回表单对象，在模板中渲染错误原因
        return HttpResponseForbidden("用户名密码格式不正确")

# 登录
class LoginView(View):
    def get(self,request):
        loginform = LoginForm()
        return render(request, 'login.html',{'loginform':loginform})

    def post(self,request):
        data = request.POST
        data_dict = data.dict()
        register_from = LoginForm(data)

        res = register_from.is_valid()

        if res:
            try:
                user = UserProfile.objects.get(email = data_dict['username'])
            except UserProfile.DoesNotExist:
                return HttpResponseForbidden("用户名不存在")
            try:
                user.check_password(data_dict['password'])
            except :
                return HttpResponseForbidden("密码错误")
            login(request, user)
            response = redirect(reverse('index'))
            response.set_cookie("username", data_dict['username'])
            return response

        return HttpResponseForbidden("用户名密码格式不正确")

# 忘记密码
class ForgetPwdView(View):
    def get(self,request):
        forget_form = ForgetForm()
        return render(request, 'forgetpwd.html', {'forget_form': forget_form})

    def post(self, request):
        data = request.POST

        register = ForgetForm(data)
        res = register.is_valid()

        register_dict = data.dict()
        if res:
            # 预处理
            try:
                UserProfile.objects.get(email=register_dict["email"])
            except UserProfile.DoesNotExist:
                return HttpResponseForbidden("email不存在")
            # 加密(加密时间15分钟,超时点击报错)
            serializer = TimedJSONWebSignatureSerializer(secret_key=settings.SECRET_KEY, expires_in=15 * 60)
            verify = serializer.dumps({"email":register_dict["email"]}).decode()
            # 发送邮件
            verify_url= settings.EMAIL_ACTIVE_URL + verify
            SendEmail(register_dict["email"], verify_url)
            return HttpResponse('邮件已经发送哦~')
        else:
            return HttpResponseForbidden("验证码或邮箱格式不正确")
# 重置密码
class ResetView(View):
    def get(self,request,active_code):

        # 解密(预处理,如果报错告知验证链接过期)
        try:
            serializer = TimedJSONWebSignatureSerializer(secret_key=settings.SECRET_KEY, expires_in=15 * 60)
            verify = serializer.loads(active_code)
        except :
            return HttpResponseForbidden("验证链接过期")
        # print(verify)
        # 判断邮箱是否使一样的
        try :
            UserProfile.objects.get(email = verify["email"])
        except UserProfile.DoesNotExist:
            return render(request,'active_fail.html')
        email = verify['email']
        # register = ModifyPwdForm()
        return render(request, 'password_reset.html',{'email':email})

    def post(self,request,active_code):
        # 获取表单数据
        register = request.POST
        # 解密
        try:
            serializer = TimedJSONWebSignatureSerializer(secret_key=settings.SECRET_KEY, expires_in=15 * 60)
            verify = serializer.loads(active_code)
        except:
            return HttpResponseForbidden("服务器繁忙")
        # 生成表单对象
        data = ModifyPwdForm(register)
        # 校验表单
        res = data.is_valid()
        register_dict = register.dict()
        if res:
            if register_dict['password1'] == register_dict['password2'] :
                UserProfile.objects.filter(email=verify["email"]).update(password=register_dict['password2'])
                response = redirect(reverse('login'))
                logout(request)
                return response
            else:
                return HttpResponseForbidden('两次输入的密码不一致')
        else:
            return HttpResponseForbidden('密码格式不正确')
# 展示注册页
class UserInfoView(LoginRequiredMixin,View):
    def get(self,request):
        return render(request, 'usercenter-info.html')
    def post(self,request):
        # 获取表单数据,判断
        data = request.POST
        # 判断时间格式,表单格式和post格式不一致.不一致就转换
        data_dict = data.dict()
        if "年" in data_dict['birthday']:
            year = data['birthday'].split("年")
            mouth = year[1].split("月")
            day = mouth[1].replace("日","")
            data_dict['birthday'] = datetime(year=int(year[0]), month=int(mouth[0]), day=int(day[0])).strftime('%Y-%m-%d')

        value = UserInfoForm(data_dict)
        res = value.is_valid()

        # 数据一致
        if res :
            # 判空判正则
            pass
            # 更新数据
            user = UserProfile.objects.get(id = request.user.id)

            user.nick_name = data_dict['nick_name']
            user.gender = data_dict['gender']
            user.birthday = data_dict['birthday']
            user.address = data_dict['address']
            user.mobile = data_dict['mobile']
            user.save()
            return JsonResponse({"status":"success"})
        else:
            return JsonResponse({"status":"error"})

# 修改头像
class UploadImageView(LoginRequiredMixin,View):

    def post(self,request):
        # 路径参数不是表单的信息,使用files接收
        image_url = request.FILES
        image_url_dict = image_url.dict()
        # print(image_url)
        # model = UploadImageForm(image_url)
        # print(model)
        # res = model.is_valid()
        # if res :

            # image_url = json.loads(request.body.decode)

        #链接数据取对象
        user = UserProfile.objects.get(id = request.user.id)
        # 保存图片地址
        try:
            user.image = image_url_dict['image']
            user.save()
        except:
            return HttpResponseForbidden("图片太大了,换张试试")
        return JsonResponse({"status":"success","msg":'头像修改成功'})
        # else:
        #     return HttpResponseForbidden('图片格式不正确')



